﻿
using Microsoft.Extensions.Primitives;
using System.Text;

public partial class BaseServices
{
    /// <summary>
    /// 搜索条件
    /// </summary>
    protected string SearchStr
    {
        get
        {
            try
            {
                string sql = "";

                //请求头获取查询参数
                var searchHeader = App.HttpContext.Request.Headers["search"];

                //如果包含参数就直接解析参数
                if (!StringValues.IsNullOrEmpty(searchHeader))
                {
                    //URLdecode
                    string json = System.Web.HttpUtility.UrlDecode(searchHeader.ToString());

                    //返序列化
                    var data = new SearchDtoModel()
                    {
                        Param = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SearchDtoModel.Item>>(json)
                    };

                    //将数据集转为sql条件字符串
                    sql = data.ToSql();
                }

                return sql;
            }
            catch (Exception)
            {
                return "";
            }
        }
    }

}

/// <summary>
/// 搜索模型
/// </summary>
public class SearchDtoModel
{
    public List<Item>? Param { get; set; }

    public class Item
    {
        public string? Name { get; set; }

        public string? Value { get; set; }

        public string? Type { get; set; }
    }

    public string ToSql()
    {
        StringBuilder result = new StringBuilder();

        result.Append("1=1");

        try
        {
            foreach (var item in Param)
            {
                if (!string.IsNullOrEmpty(item.Value))
                {
                    if (item.Type == "text" || item.Type == "select")
                    {
                        result.Append($" and {item.Name} = '{item.Value}' ");
                    }

                    if (item.Type == "like")
                    {
                        result.Append($" and {item.Name} like '%{item.Value}%' ");
                    }
                }
            }
        }
        catch
        {

        }

        return result.ToString();
    }



}
